import Vue from 'vue'
import VueRouter from 'vue-router'
import StudentManage from '../views/StudentManage.vue'
import CourseManage from '../views/CourseManage.vue'
import ClassManage from '../views/ClassManage.vue'
import StudentAdd from '../views/student/StudentAdd.vue'
import StudentList from '../views/student/StudentList.vue'
import StudentDetail from '../views/student/StudentDetail.vue'
import Login from '../views/Login.vue'
import Main from '../views/Main.vue'

Vue.use(VueRouter)

const routes = [
    {
        path: '/login',
        name: '登录页面',
        component: Login
      },
      {
        path: '/',
        component: Main,
        children: [
          {
            path: '',
            redirect: 'student'
          },
          {
            path: 'student',
            name: '学生管理',
            component: StudentManage,
            // redirect: 'student/list',
            children: [
              {
                path: 'add',
                name: '添加学生',
                component: StudentAdd
              },
              {
                path: 'list',
                name: '学生列表',
                component: StudentList,
                children: [
                  {
                    path: 'detail',
                    name: 'studentDetail',
                    component: StudentDetail
                  }
                ]
              }
            ]
          },
          {
            path: 'course',
            name: '课程管理',
            component: CourseManage
          },
          {
            path: 'class',
            name: '班级管理',
            component: ClassManage,
            beforeEnter: (to, from, next) => {
                console.log('即将进入班级管理...')
                next()
              }
          }
        ]
      }
    ]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 前置路由守卫
router.beforeEach((to, from, next) => {
    // 获取登录状态
    const isLogin = sessionStorage.getItem('isLogin')
    
    if (to.path === '/login') {
      // 如果是登录页面，直接放行
      next()
    } else {
      // 非登录页面，判断是否登录
      if (isLogin) {
        next()
      } else {
        next('/login')
      }
    }
  })
  
  // 后置路由守卫
  router.afterEach((to) => {
    // 修改网页标题
    const title = to.name || '管理系统'
    document.title = `${title}`
  })
  
export default router 